// H5打开 ↓↓↓↓↓
// import 'dart:async';
// import 'dart:html';
// import 'dart:js';
// import 'package:amap_core/amap_core.dart';
// H5打开 ↑↑↑↑↑

import 'dart:convert';

import 'package:amap_core/amap_core.dart';
import 'package:common_utils/common_utils.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
// import 'package:yp/views/order_settlement/state.dart';
// import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/services/api.dart';

import '../helper.dart';
import '../router.dart';

/// showToast二次封装
///
///

String formatNum(double num, int postion) {
  if ((num.toString().length - num.toString().lastIndexOf(".") - 1) < postion) {
    return num.toString()
        .substring(0, num.toString().lastIndexOf(".") + postion + 1)
        .toString();
  } else {
    return num.toString()
        .substring(0, num.toString().lastIndexOf(".") + postion + 1)
        .toString();
  }
}

//gyq add begin
String getDayFromTimestamp(timestamp) {
  DateTime dt = DateTime.parse(timestamp);
  var month = '';
  var day = '';
  if (dt.month.toString().length == 1) {
    month = '0' + dt.month.toString();
  } else {
    month = dt.month.toString();
  }
  if (dt.day.toString().length == 1) {
    day = '0' + dt.day.toString();
  } else {
    day = dt.day.toString();
  }
  return month + '-' + day;
}

String getyearDayFromTimestamp(timestamp) {
  if (timestamp == null) {
    return '';
  } else {
    DateTime dt = DateTime.parse(timestamp);
    var month = '';
    var day = '';
    if (dt.month.toString().length == 1) {
      month = '0' + dt.month.toString();
    } else {
      month = dt.month.toString();
    }
    if (dt.day.toString().length == 1) {
      day = '0' + dt.day.toString();
    } else {
      day = dt.day.toString();
    }
    return dt.year.toString() + '-' + month + '-' + day;
  }
}

String getMinFromTimestamp(timestamp) {
  DateTime dt = DateTime.parse(timestamp);
  var hour = '';
  var minute = '';
  if (dt.hour.toString().length == 1) {
    hour = '0' + dt.hour.toString();
  } else {
    hour = dt.hour.toString();
  }
  if (dt.minute.toString().length == 1) {
    minute = '0' + dt.minute.toString();
  } else {
    minute = dt.minute.toString();
  }
  return hour + ':' + minute;
}

//gyq add end

Map<String, dynamic> buildParams({
  String method,
  Map<String, dynamic> params,
}) {
  var reqBase64 = EncryptUtil.encodeBase64(jsonEncode(params));
  // var reqBase64 ="eyJkYXRhX3NpZ24iOjAsImNoYW5uZWxfbnVtX2lkIjo5OCwidXNlX3BsYXRmb3JtIjozLCJtb2JpbGUiOiIxMzcwMTY5MzI3NSIsInNtc192ZXJpZnlfY29kZSI6IjY1NTE0Iiwic21zX3ZlcmlmeV90b2tlbiI6Ijk2YWExZThhLTU2ZmEtNGMyMS05OWFjLWUwMzllMWY3MDU5NiIsInNtc192ZXJpZnlfdHlwZSI6ImxvZ2luIn0=";
  var timestamp = DateUtil.formatDateStr(DateTime.now().toString(),
      format: "yyyyMMddHHmmss");
  String sign = "";

  /// cache
  ///
  var salt = SpUtil.getString('salt', defValue: '');
  var sid = SpUtil.getString('sid', defValue: '');
  if (sid.isNotEmpty && salt.isNotEmpty) {
    String s = salt +
        "method" +
        method +
        "params" +
        reqBase64 +
        "sid" +
        sid +
        "timestamp" +
        timestamp +
        salt;
    var bytes = utf8.encode(s); // data being hashed
    sign = sha1.convert(bytes).toString().toLowerCase();
  } else {
    String s = reqBase64 + "20001" + timestamp + method;
    var bytes = utf8.encode(s); // data being hashed
    //sign = sha1.convert(bytes).toString().toLowerCase();
    sign = EncryptUtil.encodeMd5(s);
  }

  Map<String, dynamic> newParams = {
    "method": method,
    "app_key": "20001",
    "params": reqBase64,
    "timestamp": timestamp,
    "sign": sign,

    // "sid": sid,
  };

  return newParams;
}

//hxh

///数组转字符串
String getTaskScreen(list) {
  List tempList = [];
  String str = '';
  list.forEach((f) {
    tempList.add(f);
  });

  tempList.forEach((f) {
    if (str == '') {
      str = "$f";
    } else {
      str = "$str" "," "$f";
    }
  });

  return str;
}

setcard(state, index) {
  // state.isGiftNum = 0;
  // state.isGiftMoney =
  //     state.total["all_payment"] ?? state.total["balance_amount"];

  if (!state.GiftcardList[index]['click']) {
    if (state.isGiftMoney <= 0) {
      toast('金额已不需要选择购物卡');
    } else {
      state.GiftcardList[index]['click'] = true;
      state.isGiftNum++;
      state.isGiftMoney =
          state.isGiftMoney - state.GiftcardList[index]['money_available'];
      state.realMoney =
          state.realMoney - state.GiftcardList[index]['money_available'];
      if (state.isGiftMoney < 0.0) {
        state.isGiftMoney = 0.0;
      }
    }
  } else {
    state.GiftcardList[index]['click'] = false;
    state.isGiftNum--;
    state.realMoney =
        state.realMoney + state.GiftcardList[index]['money_available'];
    state.isGiftMoney =
        state.isGiftMoney + state.GiftcardList[index]['money_available'];
  }
  if (state.realMoney >= 0 && state.isGiftMoney >= 0.0) {
    state.isGiftMoney = state.realMoney;
  }
  state.isGiftMoney = NumUtil.getNumByValueDouble(state.isGiftMoney, 2);
}

gotomoney(state, Function startCPCNWeixinPay, params1, order_num_id) {
  var card_nos = [];
  var zong = 0.0;
  print('回调错误3');
  for (var i = 0; i < state.GiftcardList.length; i++) {
    if (state.GiftcardList[i]['click']) {
      card_nos.add(state.GiftcardList[i]['card_no']);
      zong = zong + state.GiftcardList[i]['money_available'];
    }
  }
  if (card_nos.length > 0) {
    print('2222222222222222222222');
    print(state.total["all_payment"]);
    print(state.isGiftMoney);
    var params2 = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "order_num_id": order_num_id,
      'access_token': SpUtil.getString('token'),
      "shopping_card_pays": [
        {
          "pay_type_id": 15,
          "card_nos": card_nos,
          "pay_amount": state.total["all_payment"] - state.isGiftMoney
        }
      ]
    };
    //如果选择了福利卡就先调用福利卡接口
    Api.paysubmitPayment(params2).listen((event1) {
      print('福利卡2');
      print(event1);
      //获取openid
      // getopenid();
      Api.orderPayment(params1).listen((event2) {
        if (event2['code'] == 0) {
          print(event2);
          SpUtil.putString('dingdan', event2['tml_num_id']);
          state.shifu = event2['pay_response']['coupon_fee'];
          if (zong >= state.total["all_payment"]) {
            if (SpUtil.getString('pay_type') == 'tuan') {
              Get.toNamed(RouteConfig.joinGroup);
            } else {
              Get.offNamed(RouteConfig.orderComplete, arguments: {
                'dingdan': SpUtil.getString('dingdan'),
                'shifu': event2['pay_response']['coupon_fee']
              });
            }
          } else {
            print('我要去支付了');
            print(jsonDecode(event2['pre_pay_no']));
            var payjson = jsonDecode(event2['pre_pay_no']);
            print('kIsWeb ==true');
            print(kIsWeb == true);
            if (kIsWeb == true) {
              webpay(event2['pre_pay_no']);
            } else {
              startCPCNWeixinPay(event2['pre_pay_no']);
            }
          }
        } else {
          toast(event2['message']);
        }
      });
    });
  } else {
    // getopenid();
    Api.orderPayment(params1).listen((event2) {
      if (event2['code'] == 0) {
        print('我要去支付了');
        print(params1);
        SpUtil.putString('dingdan', event2['tml_num_id']);
        state.shifu = event2['pay_response']['coupon_fee'];
        // print('kIsWeb ==true');
        // print(kIsWeb == true);
        if (kIsWeb == true) {
          webpay(event2['pre_pay_no']);
        } else {
          startCPCNWeixinPay(event2['pre_pay_no']);
        }
      } else {
        toast(event2['message']);
      }
    });
  }
}

setMoneyOver(
    tml_num_id, client_pay_result_code, String type, String payType, String s) {
  if (payType == 'success') {
    var params1 = {
      'access_token': SpUtil.getString('token'),
      "tml_num_id": tml_num_id,
      "client_pay_result_code": client_pay_result_code
    };
    print('刷新订单');
    Api.paymentFinish(params1).listen((event2) {
      if (SpUtil.getString('pay_type') == 'tuan') {
        Get.toNamed(RouteConfig.joinGroup);
      } else {
        Get.offNamed(RouteConfig.orderComplete,
            arguments: {'dingdan': tml_num_id, 'shifu': 0, type: 'b'});
      }
      // if (type == 'List') {
      //   Get.toNamed(RouteConfig.order, arguments: {'status': 0});
      // } else if (type == 'pintuan') {
      //   Get.toNamed(RouteConfig.joinGroup,
      //       arguments: {'dingdan': tml_num_id, 'shifu': 0, type: 'a'});
      // } else {
      //   if (s == 'a') {
      //     Get.toNamed(RouteConfig.orderComplete,
      //         arguments: {'dingdan': tml_num_id, 'shifu': 0, type: 'a'});
      //   } else {
      //     Get.offNamed(RouteConfig.orderComplete,
      //         arguments: {'dingdan': tml_num_id, 'shifu': 0, type: 'b'});
      //   }
      // }
    });
  } else {
    print('支付失败');
    print(type);
    if (SpUtil.getString('pay_type') == 'tuan') {
      Get.offNamed(RouteConfig.tuanOrder);
    } else if (SpUtil.getString('pay_type') == 'xiangqing') {
      Get.back();
    } else {
      Get.offNamed(RouteConfig.order, arguments: {'status': 0});
    }
    // if (type == 'List') {
    //   // Get.toNamed(RouteConfig.order, arguments: {'index': 0});
    // } else if (type == 'pintuan') {
    //   Get.toNamed(RouteConfig.joinGroup,
    //       arguments: {'dingdan': tml_num_id, 'shifu': 0, type: 'a'});
    // } else {
    //   if (s == 'a') {
    //     Get.toNamed(RouteConfig.orderComplete,
    //         arguments: {'dingdan': tml_num_id, 'shifu': 0, type: 'a'});
    //   } else {
    //     Get.offNamed(RouteConfig.orderComplete,
    //         arguments: {'dingdan': tml_num_id, 'shifu': 0, type: 'b'});
    //   }
    // }
  }
}

//去拼团详情
gopintuan(g_buy_id, shop_id) {
  Get.toNamed(
      RouteConfig.GroupDetailPage + '?g_buy_id=$g_buy_id&shop_id=$shop_id',
      arguments: {'g_buy_id': g_buy_id, 'shop_id': shop_id});
}

//分享路由导航  这些在H5没用
argumentsRouter(arguments) {
  print("argumentsargumentsarguments=$arguments");
  if (arguments['from_usr_num_id'] != null) {
    var url = Config.WEB_URL +
        "collect_coupons?usr_num_id=${arguments['from_usr_num_id']}&series=${arguments['seriesID']}";
    if (kIsWeb) {
      webpay(url);
    } else {
      Get.offAllNamed(RouteConfig.collectCoupons, arguments: {
        'usr_num_id': arguments['from_usr_num_id'],
        'series': arguments['seriesID'],
      });
    }
    //好友领券

  } else if (arguments['activity_num_id'] != null &&
      arguments['event_num_id'] != null) {
    var url = Config.WEB_URL +
        "random_amount?activity_num_id=${arguments['activity_num_id']}&event_num_id=${arguments['event_num_id']}";
    if (kIsWeb) {
      webpay(url);
    } else {
      //拼手气红包
      Get.offAllNamed(RouteConfig.randomAmount, arguments: {
        "activity_num_id": arguments['activity_num_id'],
        "event_num_id": arguments['event_num_id'],
      });
    }
  } else if (arguments['tml_num_id'] != null) {
    //分享拼团
    var url = Config.WEB_URL +
        "join_group?tml_num_id=${arguments['tml_num_id']}&login=1";
    if (kIsWeb) {
      webpay(url);
    } else {
      Get.offAllNamed(RouteConfig.joinGroup,
          arguments: {'tml_num_id': arguments['tml_num_id']});
    }
  } else if (arguments['series'] != null) {
    //发现
    // var url = Config.WEB_URL + "event_detail?series=${arguments['series']}";

    if (kIsWeb) {
      Get.offAllNamed(RouteConfig.eventDetail, arguments: arguments);
    } else {
      Get.offAllNamed(RouteConfig.eventDetail, arguments: arguments);
    }
  } else if (arguments['itemNumId'] != null) {
    // 分享商品详情页

    var url = Config.WEB_URL +
        "goods_detail?itemNumId=${arguments['itemNumId']}&styleNumId=${arguments['styleNumId']}&shopId=${arguments['shopId']}&cat1Id=${arguments['cat1Id']}&typeIndex=${arguments['typeIndex'] ?? 0}";

    if (kIsWeb) {
      webpay(url);
    } else {
      Get.toNamed(RouteConfig.goodsDetail, arguments: {
        'itemNumId': arguments['itemNumId'],
        'styleNumId': arguments['styleNumId'],
        'shopId': arguments['shopId'],
        'cat1Id': arguments['cat1Id'],
        'typeIndex': arguments['typeIndex'] ?? 0
      });
    }
  } else if (arguments['linktarget'] != null) {
    // 预售
    var url = Config.WEB_URL +
        'preSaleActive?linktarget=${arguments['linktarget']}&shopId=${arguments['shopId']}';
    if (kIsWeb) {
      webpay(url);
    } else {
      Get.toNamed(RouteConfig.preSaleActive,
          arguments: {'linktarget': arguments['linktarget']});
    }
  } else {
    Get.offAllNamed(RouteConfig.main);
  }
}

//购买物品数量
String getproNum(List cartitemlist) {
  double num = 0.0;
  cartitemlist.forEach((element) {
    if (element['quantity'] != null) {
      num = num + element['quantity'];
    }
  });
  return num.toStringAsFixed(0);
}

///大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
/// 此方法中前三位格式有：
/// 13+任意数 * 15+除4的任意数 * 18+除1和4的任意数 * 17+除9的任意数 * 147
bool isChinaPhoneLegal(String str) {
  return new RegExp(
          '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[0-9])|(147,145))\\d{8}\$')
      .hasMatch(str);
}

//判断是否有子公司商品
bool subCorShopId(List goodsItem) {
  for (var i = 0; i < goodsItem.length; i++) {
    for (var j = 0;
        j < goodsItem[i]["ec_packages"][0]["cartitemlist"].length;
        j++) {
      if (goodsItem[i]["ec_packages"][0]["cartitemlist"][j]['shop_id'] !=
          SpUtil.getInt('storeShopNum')) {
        return false;
      }
    }
  }
  return true;
}

String toConstraintLen(double num, int position) {
  if (num == null) {
    return '0';
  }
  String res;
  String numStr = num.toString();
  if (numStr.lastIndexOf('.') > 0) {
    if (position == 0) {
      res = numStr.substring(0, numStr.lastIndexOf('.'));
    } else {
      if (numStr.length - numStr.lastIndexOf('.') - 1 < position) {
        res = num.toStringAsFixed(position)
            .substring(0, num.toString().lastIndexOf('.') + position + 1);
      } else {
        res = num.toString()
            .substring(0, num.toString().lastIndexOf('.') + position + 1);
      }
    }
  } else {
    if (position == 0) {
      res = numStr;
    } else {
      res = num.toStringAsFixed(position);
    }
  }

  /// 尾数去零
  if (res.contains('.')) {
    while (true) {
      if (res.endsWith('0')) {
        res = res.substring(0, res.length - 1);
      } else {
        if (res.endsWith('.')) {
          res = res.substring(0, res.length - 1);
        }
        break;
      }
    }
  }
  return res;
}

class Utils {
  static String toConstraintLen(double num, int position) {
    if (num == null) {
      return '0';
    }
    String res;
    String numStr = num.toString();
    if (numStr.lastIndexOf('.') > 0) {
      if (position == 0) {
        res = numStr.substring(0, numStr.lastIndexOf('.'));
      } else {
        if (numStr.length - numStr.lastIndexOf('.') - 1 < position) {
          res = num.toStringAsFixed(position)
              .substring(0, num.toString().lastIndexOf('.') + position + 1);
        } else {
          res = num.toString()
              .substring(0, num.toString().lastIndexOf('.') + position + 1);
        }
      }
    } else {
      if (position == 0) {
        res = numStr;
      } else {
        res = num.toStringAsFixed(position);
      }
    }

    /// 尾数去零
    if (res.contains('.')) {
      while (true) {
        if (res.endsWith('0')) {
          res = res.substring(0, res.length - 1);
        } else {
          if (res.endsWith('.')) {
            res = res.substring(0, res.length - 1);
          }
          break;
        }
      }
    }
    return res;
  }
}

//////////////WEB方法,H5打包需要打开////////////////////////////
webpay(url) {
  // print('goto url:$url');
  // window.location.href = url;
  // print('succeeded to url:$url');
}

//获取路径参数
getQueryVariable(variable) {
  // try {
  //   var query = window.location.toString();
  //   var urls = query.split("?");
  //   if (urls.length <= 1) return false;
  //   var vars = urls[1].split("&");
  //   for (var i = 0; i < vars.length; i++) {
  //     var pair = vars[i].split("=");
  //     if (pair[0] == variable) {
  //       return pair[1];
  //     }
  //   }
  //   return (false);
  // } catch (err) {}
}

fetchH5Location() {
  // Completer completer = Completer<Map<String, dynamic>>();
  // MapOptions _mapOptions = MapOptions(
  //   zoom: 0,
  //   viewMode: '2D',
  // );
  // AMap aMap = AMap('location', _mapOptions);
  //
  // aMap.plugin(['AMap.Geolocation'], allowInterop(() {
  //   Geolocation geolocation = Geolocation(GeoOptions());
  //   aMap.addControl(geolocation);
  //
  //   geolocation.getCurrentPosition(allowInterop((status, result) {
  //     print("datadatadatadata==getCurrentPosition= ${status}");
  //
  //     if (status == 'complete') {
  //       var data = {
  //         'callbackTime': '2021-12-23 11:00:34',
  //         'locationTime': '2021-12-23 11:00:33',
  //         'locationType': 6,
  //         'latitude': result.position == null ? 0 : result.position.lat,
  //         'longitude': result.position == null ? 0 : result.position.lng,
  //         'accuracy': 550.0,
  //         'altitude': 0.0,
  //         'bearing': 0.0,
  //         'speed': 0.0,
  //         'country': result.addressComponent == null
  //             ? ''
  //             : result.addressComponent.country,
  //         'province': result.addressComponent == null
  //             ? ''
  //             : result.addressComponent.province,
  //         'city': result.addressComponent == null
  //             ? ''
  //             : result.addressComponent.city,
  //         'district': result.addressComponent == null
  //             ? ''
  //             : result.addressComponent.district,
  //         'street': result.addressComponent == null
  //             ? ''
  //             : result.addressComponent.street,
  //         // 'streetNumber':  result.addressComponent.c
  //         'cityCode': "440300",
  //         'adCode': "440300",
  //         'address': result == null ? '' : result.formattedAddress,
  //         'description': result == null ? '' : result.formattedAddress
  //       };
  //
  //       print("datadatadatadata==getCurrentPosition= ${data}");
  //
  //       completer.complete(data);
  //     } else {
  //       toast("定位失败,请开启定位权限");
  //
  //       completer.complete(null);
  //     }
  //   }));
  // }));
  // return completer.future;
}

loadingShow() {
  // if (kIsWeb) {
  //   var loadingElement = document.getElementById("loading");
  //   loadingElement?.hidden = true; // remove();
  //   loadingElement?.remove();
  // }
}

/// 判断是否为微信浏览器
bool isWechat() {
  // var ua = window.navigator.userAgent.toLowerCase();
  // var isWeixin = ua.indexOf('micromessenger') != -1;
  // if (isWeixin) {
  //   return true;
  // } else {
  //   return false;
  // }
  return false;
}
